package com.rs.portal.reserve.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.jaxplat.JaxplatBean;
import com.jaxplat.commons.Row;
import com.jaxplat.commons.RowImpl;
import com.jaxplat.exceptions.GeneralException;
import com.jaxplat.util.StringUtils;
import com.rs.commons.ApplyType;
import com.rs.commons.PayStatus;
import com.rs.commons.ReserveStatus;
import com.rs.commons.RsErrCode;
import com.rs.commons.web.PortalBaseAction;
import com.rs.rsbiz.doctor.delegate.DoctorScheduleDelegate;
import com.rs.rsbiz.reserve.delegate.ReserveDelegate;
import com.rs.rsbiz.services.ReserveFacade;
import com.rs.rsbiz.services.ReserveFactory;
import com.rs.util.IDCardValidator;
import com.rs.util.RegexUtil;
import com.rs.util.Utils;

public class ReserveWapAction extends PortalBaseAction
{
    private Log log = LogFactory.getLog(getClass());
    private DoctorScheduleDelegate dsDelegate;

    public DoctorScheduleDelegate getDsDelegate()
    {
        return dsDelegate;
    }

    public void setDsDelegate(DoctorScheduleDelegate dsDelegate)
    {
        this.dsDelegate = dsDelegate;
    }

    /**
     * <pre>
     * 第一步：从专家浏览页面进入，传入排班id，加载排班信息，forward到step1页面，
     * 在step1页面中载入专家的排班信息。
     * </pre>
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView apply(HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        Map attrs = new HashMap();
        if (null == request.getSession().getAttribute("usessionid") || StringUtils.isEmpty(request.getSession().getAttribute("usessionid")))
        {
            return new ModelAndView("unlogin", attrs);
        }
        Row param = this.parseRequestParametersToRow(request);
        if (param.containsKey("ds_id"))
        {

            try
            {
                long dsId = param.getLong("ds_id");
                Row dsInfo = dsDelegate.getDoctorSchedule(dsId);
                if (null != dsInfo)
                {
                    attrs.put("dsInfo", dsInfo);
                    return new ModelAndView("reserve_input", attrs);
                }
            }
            catch (Exception e)
            {
                attrs.put("message", "操作有错误.");
                log.info("操作有错误.", e);
            }

        }
        attrs.put("message", "预约信息不存在");

        return new ModelAndView("error", attrs);

    }

    /**
     * <pre>
     * 接收step1中用户提交的内容到confirmAppy，让用户确认订单内容，这个过程不用提交。
     * forward到step2页面。
     * </pre>
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView confirm(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Map attrs = new HashMap();
        if (null == request.getSession().getAttribute("usessionid") || StringUtils.isEmpty(request.getSession().getAttribute("usessionid")))
        {
            return new ModelAndView("unlogin", attrs);
        }
        Row param = this.parseRequestParametersToRow(request);

        if (param.containsKey("ds_id"))
        {
            try
            {
                long dsId = param.getLong("ds_id");
                Row dsInfo = dsDelegate.getDoctorSchedule(dsId);
                if (null != dsInfo)
                {
                    // if (!"0".equals(param.getString("contact_id")))
                    // {
                    // UserContractDelegate userContractDelegate =
                    // (UserContractDelegate)
                    // JaxplatBean.getBean("userContractDelegate");
                    //
                    // Row cparam = new RowImpl();
                    // cparam.addColumn("id", param.getString("contact_id"));
                    // UserContractEntity userContract =
                    // userContractDelegate.getUserContractById(cparam);
                    // if (null != userContract)
                    // {
                    // param.put("applicant_name", userContract.getName());
                    // param.put("id_no", userContract.getIdCardNo());
                    // param.put("gender", userContract.getSex());
                    // param.put("birth_date",
                    // Utils.getBirthDateFromIdNo(userContract.getIdCardNo()));
                    // param.put("birth_year",
                    // Utils.getYearFromIdNo(userContract.getIdCardNo()));
                    // param.put("birth_month",
                    // Utils.getMonthFromIdNo(userContract.getIdCardNo()));
                    // param.put("applicant_addr", userContract.getAddress());
                    // }
                    // }
                    Row checkResult = this.validateApply(param);
                    if (null == checkResult || RsErrCode.FAILED.equals(checkResult.getString("errcode")))
                    {

                        attrs.put("dsInfo", dsInfo);
                        attrs.put("validateResult", checkResult.get("msgList"));
                        return new ModelAndView("reserve_input", attrs);
                    }
                    else
                    {
                        param.put("birth_date", Utils.getBirthDateFromIdNo(param.getString("id_no")));
                        attrs.put("dsInfo", dsInfo);
                        attrs.put("orderInfo", param);
                        return new ModelAndView("reserve_confirm", attrs);

                    }
                }
            }
            catch (Exception e)
            {
                attrs.put("message", "操作有错误.");
                log.info("操作有错误.", e);
            }

        }

        attrs.put("message", "记录不存在.");

        return new ModelAndView("error", attrs);
    }

    protected Row validateApply(Row param) throws GeneralException
    {
        Row result = new RowImpl();
        List msgList = new ArrayList();
        if (null == param.getObject("id_no"))
        {
            msgList.add("身份证号码不能为空.");
        }
        if (null == param.getObject("applicant_name"))
        {
            msgList.add("患者名称不能为空.");
        }
        if (null == param.getObject("gender"))
        {
            msgList.add("性别不能为空.");
        }
        if (null == param.getObject("mobile_no"))
        {
            msgList.add("手机号不能为空.");
        }

        if (null == param.getObject("applicant_addr"))
        {
            msgList.add("住址不能为空.");
        }

        IDCardValidator idValidator = new IDCardValidator();

        try
        {
            if (!"".equals(IDCardValidator.test(param.getString("id_no").trim())))
            {
                msgList.add("无效身份证号码.");
            }
        }
        catch (Exception e)
        {
            msgList.add("无效身份证号码.");
        }

        if (!RegexUtil.isMobileNo(param.getString("mobile_no").trim()))
        {
            msgList.add("无效手机号码.");
        }
        // if (!RegexUtil.isYear(param.getString("birth_year").trim()))
        // {
        // msgList.add("出生年份不正确.");
        //
        // }
        // else
        // {
        // Calendar cal = Calendar.getInstance();
        // cal.setTime(new Date());
        // int currYear = cal.get(Calendar.YEAR);
        // int currMonth = cal.get(Calendar.MONTH) + 1;
        // int inputYear = param.getInt("birth_year");
        // int inputMonth = param.getInt("birth_month");
        // if (currYear < inputYear)
        // {
        // msgList.add("出生年份不能大于今年.");
        // }
        // else if (currYear == inputYear && currMonth < inputMonth)
        // {
        // msgList.add("出生年月不能大于当前月份.");
        // }
        // }

        if (msgList.size() > 0)
        {
            result.addColumn("msgList", msgList);
            result.addColumn("errcode", RsErrCode.FAILED);
        }
        else
        {
            result.addColumn("errcode", RsErrCode.SUCCESS);

        }
        return result;
    }

    /**
     * step2提交动作，调用ReserveFacade.
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView commit(HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        Map attrs = new HashMap();
        if (null == request.getSession().getAttribute("usessionid") || StringUtils.isEmpty(request.getSession().getAttribute("usessionid")))
        {
            return new ModelAndView("unlogin", attrs);
        }
        request.getSession().setAttribute("apply_type", ApplyType.WEB);
        Row param = this.parseRequestParametersToRow(request);

        if (param.containsKey("ds_id"))
        {
            try
            {
                long dsId = param.getLong("ds_id");
                Row dsInfo = dsDelegate.getDoctorSchedule(dsId);
                if (null != dsInfo)
                {
                    Row checkResult = this.validateApply(param);
                    if (null == checkResult || RsErrCode.FAILED.equals(checkResult.getString("errcode")))
                    {
                        attrs.put("dsInfo", dsInfo);
                        attrs.put("validateResult", checkResult.get("msgList"));
                        return new ModelAndView("reserve_input", attrs);
                    }
                    else
                    {
                        param.put("birth_date", Utils.getBirthDateFromIdNo(param.getString("id_no")));
                        Row orderInfo = new RowImpl();
                        orderInfo.putAll(param);

                        // 这里的目的是要区分，是wap,12580还是通过其他方式下的订单。
                        orderInfo.addColumn("apply_type", ApplyType.WAP);
                        orderInfo.addColumn("remote_ip", request.getRemoteAddr());
                        orderInfo.addColumn("user_id", request.getSession().getAttribute("mobile"));
                        ReserveFacade reserveFacade = ReserveFactory.getReserveFacade();

                        Row applyParam = new RowImpl();
                        applyParam.put("dsInfo", dsInfo);
                        applyParam.put("orderInfo", orderInfo);
                        applyParam.put("userid", request.getSession().getAttribute("mobile"));
                        applyParam.put("email", request.getSession().getAttribute("email"));
                        /**
                         * <pre>
                         * dsInfo,orderInfo，这两个数据非常重要。 
                         * 支付过程中将排班信息和原始订单信息一直传递到整个流程结束。
                         * 在后面还会添加以下几个,
                         * lockedOder: 锁定后的订单信息。
                         * userInfo: 接线员的信息，用于系统管理员为用户录入订单。
                         * 让所有的公共参数流转于整个流程，减少麻烦，使操作过程简洁。
                         * 
                         * </pre>
                         */

                        Row applyResult = reserveFacade.applyReserve(applyParam);
                        if (RsErrCode.SUCCESS.equals(applyResult.getString("errcode")))
                        {
                            Object ob = applyResult.get("callbackInfo");
                            attrs.putAll(applyResult);
                            return new ModelAndView("reserve_result", attrs);
                        }
                        else
                        {
                            attrs.putAll(applyResult);
                            return new ModelAndView("error", attrs);
                        }

                    }
                }
            }
            catch (Exception e)
            {
                attrs.put("message", "操作有错误.");
                log.info("操作有错误.", e);
            }

        }

        attrs.put("message", "记录不存在.");

        return new ModelAndView("error", attrs);
    }

    public ModelAndView repay(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Map attrs = new HashMap();
        if (null == request.getSession().getAttribute("usessionid") || StringUtils.isEmpty(request.getSession().getAttribute("usessionid")))
        {
            return new ModelAndView("unlogin", attrs);
        }
        request.getSession().setAttribute("apply_type", ApplyType.WEB);

        ModelAndView result = null;

        Row param = this.parseRequestParametersToRow(request);

        if (null == request.getSession().getAttribute("usessionid"))
        {
            attrs.put("message", "用户未登录,请先登录.");
            result = new ModelAndView("error", attrs);
            return result;
        }
        if (param.containsKey("orderId"))
        {
            String userId = (String) request.getSession().getAttribute("usessionid");
            String orderId = param.getString("orderId");
            ReserveDelegate reserveDelegate = (ReserveDelegate) JaxplatBean.getBean("reserveDelegate");
            Row orderInfo = reserveDelegate.getUserOrderById(orderId, userId);

            long reserveStatus = orderInfo.getLong("reserve_status");
            long payStatus = orderInfo.getLong("pay_status");
            if (reserveStatus != ReserveStatus.LOCKED_ORDER && payStatus != PayStatus.UNPAY)
            {
                attrs.put("message", "无效预约订单, 请重新选择预约的医生和时间.");
                return new ModelAndView("error", attrs);
            }
            long dsId = orderInfo.getLong("ds_id");
            Row dsInfo = dsDelegate.getDoctorSchedule(dsId);

            orderInfo.addColumn("apply_type", ApplyType.WAP);
            orderInfo.addColumn("remote_ip", request.getRemoteAddr());

            Row applyParam = new RowImpl();
            applyParam.put("dsInfo", dsInfo);
            applyParam.put("orderInfo", orderInfo);
            applyParam.put("userid", request.getSession().getAttribute("usessionid"));
            applyParam.put("email", request.getSession().getAttribute("email"));

            ReserveFacade reserveFacade = ReserveFactory.getReserveFacade();
            Row applyResult = reserveFacade.applyReserve(applyParam);
            if (RsErrCode.SUCCESS.equals(applyResult.getString("errcode")))
            {
                Object ob = applyResult.get("callbackInfo");
                attrs.putAll(applyResult);
                result = new ModelAndView("reserve_result", attrs);
            }
            else
            {
                attrs.putAll(applyResult);
                result = new ModelAndView("error", attrs);
            }
        }
        else
        {
            attrs.put("message", "记录不存在.");
            result = new ModelAndView("error", attrs);
        }
        return result;
    }
}
